import { Card, FormProps, Space, Table, TableProps, Tag, Image } from "antd"

import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { DishStatus } from "@/utils/enum";
import { message, modal } from "@/utils/AntdGlobal";
import { DishItem, DishParams } from "@/types/dish";
import { deleteDishApi, getDishListApi, updateStatusApi } from "@/api/dish";
import { useCatetory } from "@/hooks/useCatetory";
import "./index.scss"
export const Component = () => {
  const { Option } = Select;
  const columns: TableProps<DishItem>['columns'] = [
    {
      title: '菜品名称',
      dataIndex: 'name',
      key: 'name',
      align: "center"
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'image',
      align: "center",
      render: (data: string) => {
        return <Image width={30} src={data} />
      }
    },
    {
      title: '菜品分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      align: "center"
    },
    {
      title: '售价',
      dataIndex: 'price',
      key: 'price',
      align: "center",
      render: (data: number) => {
        return <div>￥{data}</div>
      }
    },
    {
      title: '售卖状态',
      dataIndex: 'status',
      key: 'status',
      align: "center",
      render: (data: number) => {
        return <Tag color={DishStatus[data].type}>{DishStatus[data].name}</Tag>
      }
    },
    {
      title: '最后操作时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      align: "center"
    },
    {
      title: '操作',
      align: "center",
      render: (data: DishItem) => {
        return (
          <Space size="middle">
            <a style={{ color: "#0e8b8d" }} onClick={() => editDish(data)}>修改</a>
            <a style={{ color: "red" }} onClick={() => deleteDish(data)}>删除</a>
            <a style={{ color: data.status ? "red" : "#0e8b8d" }} onClick={() => updateStatus(data)}>{data.status ? '停售' : '启售'}</a>
          </Space >
        )
      },
    },
  ];
  // 定义数据
  const [dishList, setDishList] = useState<DishItem[]>([])
  // 定义总数
  const [total, setTotal] = useState(0)
  // 获取菜品分类
  const { categoryList } = useCatetory()
  // 定义选择的数据id
  const [ids, setIds] = useState<React.Key[]>([])
  // 跳转
  const navigate =  useNavigate()
  // 定义参数
  const [dishQuery, setDishQuery] = useState<DishParams>({
    name: '',
    categoryId: undefined,
    status: undefined,
    page: 1,
    pageSize: 10
  })
  // 修改页码
  const changePage = (page: number, pageSize: number) => {
    setDishQuery({
      ...dishQuery,
      page,
      pageSize,
    })
  }
  // 获取数据
  useEffect(() => {
    const getDishList = async () => {
      // 发请求获取数据
      const res = await getDishListApi(dishQuery)
      const { data } = res
      setTotal(data.total)
      setDishList(data.records)
    }
    getDishList()
  }, [dishQuery])
  type FieldType = {
    name?: string,
    categoryId?: number,
    status?: number
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setDishQuery({
      ...dishQuery,
      name: values.name,
      status: values.status,
      categoryId: values.categoryId
    })
  };
  // 修改状态
  const updateStatus = (data: DishItem) => {
    modal.confirm({
      title: data.status ? '停售菜品' : '启售菜品',
      icon: <ExclamationCircleOutlined />,
      content: '确认调整该菜品的状态?',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let status = data.status ? 0 : 1
        const res = await updateStatusApi(data.id, status)
        if (res.code === 1) {
          message.success(`该分类${data.status ? '停售成功' : '启售成功'}`)
          setDishQuery({
            ...dishQuery,
            page: 1,
            pageSize: 10,
            name: dishQuery.name
          })
        }
      }
    });
  }
  // 删除菜品
  const deleteDish = (data: DishItem) => {
    modal.confirm({
      title: '删除菜品',
      icon: <ExclamationCircleOutlined />,
      content: '确认要删除菜品嘛?',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await deleteDishApi([data.id].join(''))
        if (res.code === 1) {
          message.success('删除成功')
          setDishQuery({
            ...dishQuery,
            page: 1,
            pageSize: 10,
            name: dishQuery.name
          })
        }
      }
    });
  }
  // 批量删除菜品
  const deleteBatch = () => {
    if (ids.length === 0) return message.error("请先选择菜品！")
    modal.confirm({
      title: '删除菜品',
      icon: <ExclamationCircleOutlined />,
      content: '确认要批量删除这些菜品嘛?',
      centered: true,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await deleteDishApi(ids.join(','))
        if (res.code === 1) {
          message.success('删除成功')
          setDishQuery({
            ...dishQuery,
            page: 1,
            pageSize: 10,
            name: dishQuery.name
          })
        }
      }
    });
  }
  // 全选
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setIds(newSelectedRowKeys)
  };
  // 修改
  const editDish = (data: DishItem) => {
    navigate(`/dish/addDish?id=${data.id}`)
  }
  // 添加
  const addDish = () => {
    navigate("/dish/addDish")
  }
  return (
    <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
      {/* 查询 */}
      <Card className="mb-4">
        <div className="flex flex-justify-between">
          <Form
            name="basic"
            layout="inline"
            labelCol={{ span: 8 }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="菜品名称"
              name="name"
            >
              <Input placeholder="请输入菜品名称" allowClear />
            </Form.Item>
            <Form.Item<FieldType> style={{ width: 250 }} name="categoryId" label="菜品分类">
              <Select
                placeholder="请选择菜品分类"
                allowClear
              >
                {categoryList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
              </Select>
            </Form.Item>
            <Form.Item<FieldType> style={{ width: 250 }} name="status" label="售卖状态">
              <Select
                placeholder="请选择售卖状态"
                allowClear
              >
                <Option value={1}>启售</Option>
                <Option value={0}>停售</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
          <div>
            <Button type="primary" icon={<DeleteOutlined />} danger style={{ marginRight: "10px" }} onClick={deleteBatch}>
              批量删除
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={addDish}>
              新建菜品
            </Button>
          </div>
        </div>
      </Card>
      {/* 表格 */}
      <Card style={{ overflow: 'auto', height: 'calc(100% - 98px)' }}>
        <Table<DishItem> rowKey="id" bordered dataSource={dishList} columns={columns} pagination={
          {
            total: total,
            showQuickJumper: true,
            showSizeChanger: true,
            showTotal: (total) => `总数 ${total} 条`,
            position: ["bottomCenter"],
            onChange: (page, pageSize) => changePage(page, pageSize)
          }
        } rowSelection={{ type: "checkbox", onChange: onSelectChange }} />
      </Card>
    </div>
  )
}
